package com.slg.android.manyanime;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.cache.MD5FileNameGenerator;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.slg.android.manyanime.bean.User;
import com.slg.android.manyanime.utils.ApiUtils;
import com.slg.android.manyanime.utils.DataStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;


public class LoginActivity extends FragmentActivity implements Handler.Callback, PlatformActionListener {
    @ViewInject(R.id.login_phone_editText)
    private EditText phone;
    @ViewInject(R.id.login_password_editText)
    private EditText password;
    private HttpUtils httpUtils;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        ViewUtils.inject(this);
        httpUtils = new HttpUtils();
    }

    @OnClick({R.id.login_login_textView,R.id.login_login_by_sina})
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.login_login_textView:
                Editable mobile = phone.getText();
                Editable pass = password.getText();
                if (!(TextUtils.isEmpty(mobile) || TextUtils.isEmpty(pass))) {
                    String md5Pass = new MD5FileNameGenerator().generate(pass.toString());
                    httpUtils.send(HttpRequest.HttpMethod.GET
                            , ApiUtils.LOGIN + "&mobile=" + mobile.toString() + "&password=" + md5Pass
                            , new CallBack());
                }
                break;
            case R.id.login_login_by_sina:
                //初始化ShareSDK
                ShareSDK.initSDK(this);
                //获取新浪微博的用户
                authorize(new SinaWeibo(this));
                break;
            case R.id.login_login_by_qq:
                //初始化ShareSDK
                ShareSDK.initSDK(this);
                //获取新浪微博的用户
                authorize(new QQ(this));
                break;
        }
    }

    private void authorize(Platform plat) {

        if (plat == null) {
            //如果没有指定平台，那么现在强制选择新浪微博
            plat = new SinaWeibo(this);
//            popupOthers();
//            return;
        }
        //判断指定平台是否已经完成授权
        if(plat.isValid()) {
            String userId = plat.getDb().getUserId();
            if (userId != null) {
                //用于发送注册、登录成功的消息
                UIHandler.sendEmptyMessage(1, this);
//                login(plat.getName(), userId, null);

                Log.d("Login", plat.getName());
                Log.d("Login",userId);
                return;
            }
        }

        //用于监测用户在登录的时候操作的状态
        //当用户授权成功，会进行回调，回调内部 信息
        plat.setPlatformActionListener(this);
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(true);
        //获取用户资料
        plat.showUser(null);
    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> stringObjectHashMap) {

        //获取哪一个平台的登录授权信息
        String name = platform.getName();
        //获取特定平台下面的数据库
        PlatformDb db = platform.getDb();

        //获取用户的名称
        String userName = db.getUserName();
        Log.d("Login",name +"-->"+userName);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }

    private class CallBack extends RequestCallBack<String> {

        @Override
        public void onSuccess(ResponseInfo<String> stringResponseInfo) {
            String json = stringResponseInfo.result;
            try {
                JSONObject jsonObject = new JSONObject(json);
                String flag = jsonObject.getString("flag");
                if ("1".equals(flag)) {//登陆成功
                    User user = new User();
                    user.parseData(jsonObject.getJSONObject("user"));
                    DataStore.getDataStore().setUser(user);
                    //TODO 用户数据存到数据库
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("login","login");
                    startActivity(intent);
                } else {
                    String msg = jsonObject.getString("msg");
                    Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(HttpException e, String s) {
            Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
        }
    }


}
